package org.javaboy.my_login_page.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
public class HelloController {

    /**
     * 默认情况下，登录用户的数据存在 SecurityContextHolder 中，默认是使用 ThreadLocal。
     * 但是在我们的 Web 工程中，登录请求到达之后，Tomcat 从线程池拿一个线程出来处理登录请求
     *
     * @return
     */
    @RequestMapping("/hello")
    public String hello(HttpSession httpSession) {
        //获取登录成功之后的用户对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("authentication = " + authentication);
        new Thread(() -> {
            Authentication authentication2 = SecurityContextHolder.getContext().getAuthentication();
            System.out.println("authentication2 = " + authentication2);
            SecurityContext sc = (SecurityContext) httpSession.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            System.out.println("sc.getAuthentication() = " + sc.getAuthentication());
        }).start();
        return "hello";
    }

    /**
     * 这两个参数会默认解析出来，类似于 HttpSession、HttpServletRequest
     *
     * @param authentication
     * @param principal
     * @return
     */
    @GetMapping("/user")
    public String user(Authentication authentication, Principal principal) {
        System.out.println("authentication = " + authentication);
        System.out.println("principal = " + principal);
        return "hello user";
    }


    @GetMapping("/hello2")
    public void hello2(HttpServletRequest request) {
//        new Thread(() -> {
        //获取登录用户名
        String remoteUser = request.getRemoteUser();
        //判断用户是否具备 admin 角色
        boolean admin = request.isUserInRole("admin");
        //获取当前登录用户对象
        Principal userPrincipal = request.getUserPrincipal();
        System.out.println("remoteUser = " + remoteUser);
        System.out.println("admin = " + admin);
        System.out.println("userPrincipal = " + userPrincipal);
//        }).start();
    }
}
